<?php
/**
 *
 * HotMoodRecord model class file
 *
 * @category   UC
 * @author     张丽媛 <zhangliyuan@snda.com>
 * @copyright  2010-2010 SDO UC Group
 * @version    Release: 1.0.0
 * @link       http://www.sdo.com
 * @modified   2010-3-31 20:20
 */

require_once(dirname(__FILE__).'/../../config/UCConfMacro.php');
require_once(dirname(__FILE__).'/../../config/UCConfTwitter.php');
require_once(dirname(__FILE__).'/../../libraries/UCLibPDOFactory.php');
require_once(dirname(__FILE__).'/../../libraries/UCLibCache.php');

class UCModHotMoodRecord{
	private $_cache;
	private $_errno;
	private $_included = false;

	const HOT_TWITTER_PARAMS_ERROR  = -1;
	const HOT_TWITTER_TOTAL_DB_ERROR= -2;
	const HOT_TWITTER_LIST_DB_ERROR = -3;
	const HOT_TWITTER_INSERT_DB_ERROR = -4;
	const HOT_TWITTER_DELETE_DB_ERROR = -5;


    static $errorArray = array(
        self::HOT_TWITTER_PARAMS_ERROR   =>"Params Error",  
        self::HOT_TWITTER_TOTAL_DB_ERROR => "Hot Total DB Opretion Error",
		self::HOT_TWITTER_LIST_DB_ERROR  => "Hot List DB Opretion Error",  
		self::HOT_TWITTER_INSERT_DB_ERROR  => "Hot Insert DB Opretion Error",
		self::HOT_TWITTER_DELETE_DB_ERROR  => "Hot Delete DB Opretion Error",
    );

	function __construct(){
		$this->_cache = new UCLibCache(TWITTER_MCACHE_CHANNEL_NAME);
	}

	function __destruct(){
		$this->_cache->close();
	}

	/**
	 * @purpose: 统一获取错误信息
     * @return : 错误提示
	 */
	public function getErrorInfo() {
		$error_info = array();
		$error_info['error_no'] = $this->_errno;
		$error_info['error_msg'] = self::$errorArray[$this->_errno];
		return $error_info;
	}
    

	
	/**
	 * @purpose:从cache中 取得全部热门twitter列表
	 * @params int type:查询的类型：0全部，2 图片，3视频
	 * @params int start:记录起始位置
	 * @params int limit:需要取的记录长度
	 * @return array or false array(0=>array(),1=>array())
	 */
	function getAllHotMoodRecordList($type,$start=0,$limit=TWITTER_DB_PAGE_SIZE){
		if($start < 0) $start = 0;
		$end = intval(TWITTER_DB_PAGE_SIZE)*2;
		if($start < $end){//前2页进行缓存
            $mem_key = UCConfTwitter::getMemHotTwitterPageKey($type,$start,$limit);
		    $listinfo = $this->_cache->read($mem_key);
			if(false === $listinfo){  
				$listinfo = $this -> getDBAllHotMoodRecordList($type,$start,$limit);
                if(is_array($listinfo)) {
				   $this->_cache->write($mem_key, $listinfo, HOT_TWITTER_MCACHE_EXPIRE_TIME);
				   $this->_cache->close();
			    }
			}	
		}else{
			$listinfo = $this->getDBAllHotMoodRecordList($type,$start,$limit);
		}
		return $listinfo;
	}
 

	/**
	 * @purpose: 从db中按页取得热门twitter列表
	 * @params int type:查询的类型：0全部，1文字，2 图片，3视频，4转推
	 * @params int start:记录起始位置
	 * @params int limit:需要取的记录长度
	 * @return array or false
	 */
	function getDBAllHotMoodRecordList($type,$start,$limit){
		$pdo = UCLibPDOFactory::getPDO(PDO_HOT_TAGNAME,'','twitter2dbconfig');

        if($type == 4){//转帖
			$list  = $pdo -> query_with_prepare("select * from $pdo->database.$pdo->table where conveyed_flag = 1 order by add_time desc limit ?,?",array($start,$limit));
		}else if($type == 0){
		   $list  = $pdo -> query_with_prepare("select * from $pdo->database.$pdo->table order by add_time desc limit ?,?",array($start,$limit));
		}else if($type > 1 && $type <4){
			$list  = $pdo -> query_with_prepare("select * from $pdo->database.$pdo->table where type= ? order by add_time desc limit ?,?",array($type,$start,$limit));
		}

        if(false === $list) {
			
			$this->_errno =  self::HOT_TWITTER_LIST_DB_ERROR ;
			return false;
		}else if(!is_array($list)){
			$list = array();
		}
		return $list;
	}


	/**
	 * @purpose:从cache中 取得全部热门twitter列表
	 * @params int type:查询的类型：0全部，2 图片，3视频
	 * @params int start:记录起始id位置
	 * @params int limit:需要取的记录长度
	 * @return array 
	 */
	function getNewHotMoodRecordList($type,$start_id,$limit=TWITTER_DB_PAGE_SIZE){
		if($limit < TWITTER_DB_PAGE_SIZE){
			$limit = TWITTER_DB_PAGE_SIZE;
		}
		$mem_key = UCConfTwitter::getMemHotTwitterPageKey($type,0,$limit);//获取第一页的缓存
		$listinfo = $this->_cache->read($mem_key);
		if(false === $listinfo){  
			$listinfo = $this -> getDBAllHotMoodRecordList($type,0,$limit);
			if (is_array($listinfo)) {
			   $this->_cache->write($mem_key, $listinfo, HOT_TWITTER_MCACHE_EXPIRE_TIME);
			   $this->_cache->close();
			} 
		}
		$new_info = array();
		$stop = false;//记录找到起点位置
		if(is_array($listinfo) && count($listinfo) > 0){
			foreach($listinfo as $key => $value){//倒序排列的
				if($value['mood_id']!= $start_id){
					$new_info[] = $value; //记录新信息
				}else{
					$stop = true;
					break;
				}
			}
		}	
		return $new_info;
	}

	/**
	 * @purpose: 取得热门推他的总数
	 * @params int type:查询的类型：0全部，1 文字 2 图片，3视频 4转推
	 * @return  int  次数
	 */
	 function  getAllHotMoodCount($type){
		$mem_key = UCConfTwitter::getMemcacheHotTwitterTotalKey($type);//返回热门推他总数的cachekey
		$total = $this->_cache->read($mem_key);
		$this->_cache->close();
		if(false === $total){
			$total = $this -> getDBAllHotMoodCount($type);
			$this->_cache->write($mem_key,$total,HOT_TWITTER_MCACHE_EXPIRE_TIME);
			$this->_cache->close();
		}
		return $total;
	 }

	 
	/**
	 * @purpose:从db 取得热门推他的总数
	 * @params int type:查询的类型：0全部，1 文字 2 图片，3视频 4转推
	 * @return  int  次数
	 */
	 public function getDBAllHotMoodCount($type){
		$pdo = UCLibPDOFactory::getPDO(PDO_HOT_TAGNAME,'','twitter2dbconfig');
		if($type == 4){
			$total_arr = $pdo -> query_one_row_with_prepare("select count(1) as num from $pdo->database.$pdo->table where conveyed_flag = 1");
			if(false === $total_arr){
				$this->_errno = self::HOT_TWITTER_TOTAL_DB_ERROR ;
				return false;
			}else{
				return $total_arr['num'];
			}
		}else if($type == 0){
			$type_str ="";
			$value = array();
		}else if($type > 1 && $type <4){
			$type_str =" where type=? ";
			$value = array($type);
		}
		$total_arr = $pdo -> query_one_row_with_prepare("select count(1) as num from $pdo->database.$pdo->table ".$type_str,$value);
		if(false === $total_arr){
			$this->_errno = self::HOT_TWITTER_TOTAL_DB_ERROR ;
			return false;
		}else{
			return $total_arr['num'];
		}
	 }

	 /**
	 * @purpose: 插入一条记录到热门表中
	 * @params array data:用户信息数组
	 * @return :true or false
	 */
	public function addOneHotMood($data){
		$pdo = UCLibPDOFactory::getPDO(PDO_HOT_TAGNAME,'','twitter2dbconfig');
		//如果键值重复则修改发表时间
		$result  = $pdo -> insert($data,null,array('release_time'=>$data['release_time']));
		if(false === $result){
			$this->_errno = self::HOT_TWITTER_INSERT_DB_ERROR;
			return false;
		}
		return $result;
	}

	/**
	 * @purpose:删除一条记录
	 * @params int mood_id:记录id
	 * @return :true or false
	 */
	public function deleteOneHotMood($mood_id){
		$pdo = UCLibPDOFactory::getPDO(PDO_HOT_TAGNAME,'','twitter2dbconfig');
		$data  = $pdo -> query_with_prepare("select * from $pdo->database.$pdo->table where mood_id=? ",array($mood_id));
		if(is_array($data)&& count($data)>0){
			$mood_info = $data[0];
			$result  = $pdo -> exec_with_prepare("delete from $pdo->database.$pdo->table where mood_id =?",array($mood_id));
			if(false === $result){
				$this->_errno = self::HOT_TWITTER_DELETE_DB_ERROR;
				return false;
			}else{
				//重新获取热门记录全部类型以及相应类型的首页cache
				if($mood_info['conveyed_flag']==1){
					$type = 4;
				}else{
					$type = $mood_info['type'];
				}
				$this -> reCreatetHotPageCache($mood_info['type']);	
			}
		}
		return $result;
	}

	/**
	* @purpose:重新获取热门记录前2页cache，写入
	* @return :true or false
	*/
	function reCreatetHotPageCache($type){	
		for($page = 1;$page < 3;$page++){
			//总数
			$total = $this -> getDBAllHotMoodCount($type);
			$mem_total_key = UCConfTwitter::getMemcacheHotTwitterTotalKey($type);
			$this->_cache->write($mem_total_key,$total,HOT_TWITTER_MCACHE_EXPIRE_TIME);
			$this->_cache->close();

			$start = ($page -1) *TWITTER_DB_PAGE_SIZE;
			$listinfo = $this -> getDBAllHotMoodRecordList($type,$start,TWITTER_DB_PAGE_SIZE);
			$mem_key = UCConfTwitter::getMemHotTwitterPageKey($type,$start,TWITTER_DB_PAGE_SIZE);
			if (is_array($listinfo)) {
				 $this->_cache->write($mem_key, $listinfo, HOT_TWITTER_MCACHE_EXPIRE_TIME);
				 $this->_cache->close();
			}
		}
	}

	

	/**
	 * @purpose: 实时更新热门推他首页缓存,根据插入的时间排序
	 * @params int type:类型
	 * @params int data:记录
	 */
	function  updateMoodListPage1Cache($type,$data){
		  $mem_key = UCConfTwitter::getMemHotTwitterPageKey($type,0,TWITTER_DB_PAGE_SIZE);//返回首页的cachekey
		  $oldlistinfo = $this->_cache->read($this->$mem_key);
		  $this->_cache->close();
		  $listinfo = array();
		  if(false === $oldlistinfo){
			  $listinfo = $this -> getDBAllHotMoodRecordList($type,0,TWITTER_DB_PAGE_SIZE);
		  }else if(is_array($oldlistinfo) && count($oldlistinfo)> 0){
			  if(count($oldlistinfo)==20){
			     array_pop($oldlistinfo);//移除最旧的记录
			     array_unshift($oldlistinfo,$data);//把该条记录插入最初位置
				 $listinfo = $oldlistinfo;
			  }else{
				 array_unshift($oldlistinfo,$data);//把该条记录插入最初位置
				 $listinfo = $oldlistinfo;
			  }
		  }else{
			  $listinfo[] = $data;
		  }
		  $this->_cache->write($mem_key, $listinfo, HOT_TWITTER_MCACHE_EXPIRE_TIME);
		  $this->_cache->close();
		  return;
	  }
}